#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/22 10:36
import json
from os import path, sep
from typing import List

from config.config import config
from domain.report.common.period_enum import PeriodEnum
from domain.report.dto.profit_dto import ProfitDTO
from domain.report.spider.xbrl_sse.profit_spider import profit_spider
from domain.report.spider.xbrl_sse.assembler.profit_assembler import xbrl2dtos


prefix_path = path.join(config.get("data", "folder"), "report")


def insert(dto:ProfitDTO) -> bool:
    if not dto or contain(dto):
        return False
    basic_path = f"{prefix_path}{sep}{dto.stock_code}{sep}profit_{dto.period}.json"
    with open(basic_path, "a", encoding="utf-8") as file:
        file.write(json.dumps(dto.__dict__))
        return True


def insert_batch(dto_list:List[ProfitDTO]) -> bool:
    if not dto_list or len(dto_list) == 0:
        return False
    for dto in dto_list:
        if not contain(dto):
            insert(dto)
    return True


def get(stock_code:str, year:int, period:PeriodEnum, is_consolidate:bool=False) -> ProfitDTO:
    basic_path = f"{prefix_path}{sep}{stock_code}{sep}profit_{period}.json"
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            basic_info_dict = json.loads(line)
            if basic_info_dict["year"] == year and basic_info_dict["is_consolidate"] == is_consolidate:
                basic_info = ProfitDTO()
                basic_info.__dict__ = basic_info_dict
                return basic_info
    profit_dict = profit_spider(stock_code, year, period)
    dto_list = xbrl2dtos(profit_dict, stock_code, period)
    insert_batch(dto_list)
    for dto in dto_list:
        if dto.year == year:
            return dto
    return None


def contain(dto:ProfitDTO) -> bool:
    if not dto:
        return False
    basic_path = f"{prefix_path}{sep}{dto.stock_code}{sep}profit_{dto.period}.json"
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            profit_dict = json.loads(line)
            if dto.stock_code == profit_dict["stock_code"] and dto.period == profit_dict["period"]:
                return True
    return False